//
//  XQtransitioningDelegate.swift
//  LXQWB
//
//  Created by 江海天 on 2017/7/7.
//  Copyright © 2017年 江海天. All rights reserved.
//

import UIKit
let XQpresent = NSNotification.Name(rawValue: "present")
let XQdismiss = NSNotification.Name(rawValue: "dismiss")
class XQtransitioning: NSObject,UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning {
	var isPresent = true
	var presented:UIViewController? = nil
	func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
		
		NotificationCenter.default.post(name: XQpresent, object: nil)
		self.presented = presented
		isPresent = true
		return self
	}
	
	func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{
		//NotificationCenter.default.post()
		NotificationCenter.default.post(name: XQdismiss, object: nil)
		isPresent = false
		return self
	}
	
	
	func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?
	{
		return PopoverPresentationVC(presentedViewController: presented, presenting: presenting)
	}


	func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval{
		return 0.5
	}
	
	
	public func animateTransition(using transitionContext: UIViewControllerContextTransitioning){
		let containerView = transitionContext.containerView
		if isPresent {
			
			//var fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)
			let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)
			let btn = UIButton()
			btn.addTarget(self, action: #selector(over(sender:)), for: .touchUpInside)
			containerView.addSubview(btn)
			containerView.addSubview(toView!)
		 toView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0)
			toView?.transform = CGAffineTransform(scaleX: 1.0, y: 0.0)
			
			UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
				
				toView?.transform = CGAffineTransform.identity
			}) { (_) in
				transitionContext.completeTransition(true)
			}
			
		}else{
			let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)
			UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
				fromView?.transform = CGAffineTransform.init(scaleX: 1.0, y: 0.00001)
			}, completion: {  (_) in
				transitionContext.completeTransition(true)
			})
			
			
		}
	}
	@objc private func over(sender:UIButton){
		presented?.dismiss(animated: true, completion: nil)
		NLog(message: "")
	}


}

